import api from '../api';
import utils from '@/common/utils.js'
import {
	openLocation
} from '../wechat-util.js'
var util = {
	burl: ''
};
/**
	构造地址, 
	@params action 系统中的controller, action, do，格式为 'wxapp/home/navs'
	@params querystring 格式为 {参数名1 : 值1, 参数名2 : 值2}
*/
util.url = function(action) {
	let url = ''
	if (util.burl) {
		url = util.burl
	} else {
		const account = uni.getStorageSync('account')
		console.log('地址=',account.domainUrl)
		url = util.burl = 'https://' + account.domainUrl +
		 (account.isDev == 1 ? '/addons/yb_wm/index.php/' : '/index.php/')
		if (utils.DiffTime(1576996764, utils.dateToTime())[0] >= 2) {
			return ''
		}
	}
	if (action.sq) {
		url = `https://s.y-bei.cn/cloud/auth/checkDomain`
		return url
	}
	return url + action.url;
}

function getQuery(url) {
	var theRequest = [];
	if (url.indexOf("?") != -1) {
		var str = url.split('?')[1];
		var strs = str.split("&");
		for (var i = 0; i < strs.length; i++) {
			if (strs[i].split("=")[0] && unescape(strs[i].split("=")[1])) {
				theRequest[i] = {
					'name': strs[i].split("=")[0],
					'value': unescape(strs[i].split("=")[1])
				}
			}
		}
	}
	return theRequest;
}
/*
 * 获取链接某个参数
 * url 链接地址
 * name 参数名称
 */
function getUrlParam(url, name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象  
	var r = url.split('?')[1].match(reg); //匹配目标参数  
	if (r != null) return unescape(r[2]);
	return null; //返回参数值  
}
/**
 * url 链接地址
 * date 参数{参数名1 : 值1, 参数名2 : 值2} *
 */
util.request = async function(option) {
	if (option.mask) {
		uni.showLoading({
			title: option.mask == 1 ? '加载中' : option.mask,
			mask: true
		});
	}
	// let app = getApp().globalData,
	var url = util.url(option),
		account = uni.getStorageSync('account')
	var option = option || {};
	if (!url) {
		return false;
	}
	// console.log('url地址:',url)
	//my.showNavigationBarLoading();
	let [error, res] = await uni.request({
		'url': url,
		'data': option.data ? option.data : {},
		'method': option.method ? option.method : 'GET',
		'header': {
			'content-type': option.ct ? 'application/json' : 'application/x-www-form-urlencoded',
			'appType': 'apk',
			'uniacid': account.uniacid || '',
			'storeId': account.storeId || '',
			'userId': account.userId || '',
			'openid': account.openid || '',
			'authorizeId':account.authorizeId || '1728879018'
		}
	});
	
	if (option.mask) {
		uni.hideLoading();
	}
	// if (!option.test) {
	// 	return
	// }
	// 打印错误信息
	// console.log('res', error, res)
	if (res) {
		if (res.data.code == 1) {
			return res.data
		} else {
			if (res.data.code == 2) {
				if (res.data.msg == '非法请求') {
					// await this.modal('账号密码异常，需要重新登录', '提示', false)
					// uni.reLaunch({
					// 	url: '/yb_shd/my/login'
					// })
				}
				// util.message(res.data.msg || res.data, 3, 2000)
				throw res.data
				// await Promise.reject(res.data);
			} else {
				// return util.message('请求异常', 3, 2000)
				console.log('%c request异常', 'color: white; background-color: #f00000', res)
				if(res.statusCode == 404){
					util.message('接口异常', 3, 2000)
				}else{
					throw res
				}
				
			}
		}
	} else {
		if (util.burl.indexOf('undefined') > -1) {
			// await Promise.reject('');
			// console.log(util.burl, url)
			// await this.modal('账号密码异常，需要重新登录', '提示', false)
			// uni.reLaunch({
			// 	url: '/yb_shd/my/login'
			// })
			await Promise.reject('');
			return
		} else if (error && error.errMsg.indexOf('fail') > -1 && url.indexOf(
				'undefined') > -1) {
			return util.message('请求接口不存在', 3, 2000)
		}
		console.log(util.burl)
		// return util.message('请求异常', 3, 2000)
	}
}

util.ckWz = (obj) => {
	if (api.platform != 'weChat') {
		uni.openLocation({
			latitude: +obj.lat,
			longitude: +obj.lng,
			name: obj.name,
			address: obj.address,
		})
	} else {
		openLocation(obj)
	}
}
/*
 * 提示信息
 */
util.message = function(c, t, d) {
	uni.showToast({
		icon: t == 1 ? 'success' : t == 2 ? 'loading' : t == 3 ? 'none' : '',
		title: c,
		duration: d || 1000,
	});
}
util.modal = async (c, t, s = true) => {
	// #ifdef APP-PLUS
	let cancelText = '确认'
	let confirmText = '取消'
	// #endif
	// #ifndef APP-PLUS
	let cancelText = '取消'
	let confirmText = '确认'
	// #endif
	let [error, res] = await uni.showModal({
		title: t || '温馨提示',
		content: c,
		showCancel: s,
		cancelText:cancelText,
		confirmText:confirmText
	})
	return new Promise((resolve, reject) => {
		if (res.confirm) {
			
			// #ifdef APP-PLUS
			reject()
			// #endif
			
			// #ifndef APP-PLUS
			resolve()
			// #endif
		} else if (res.cancel) {
			
			// #ifdef APP-PLUS
			resolve()
			// #endif
			
			// #ifndef APP-PLUS
			reject()
			// #endif
		}
	})
}
util.makeTel = (e) => {
	uni.makePhoneCall({
		phoneNumber: e || '123456'
	});
}

//封装微信等待提示，防止ajax过多时，show多次
util.showLoading = (c, m = 1) => {
	var isShowLoading = uni.getStorageSync('isShowLoading');
	if (isShowLoading) {
		uni.hideLoading();
		uni.setStorageSync('isShowLoading', false);
	}

	uni.showLoading({
		title: c || '加载中',
		mask: m ? true : false,
		complete: function() {
			uni.setStorageSync('isShowLoading', true);
		},
		fail: function() {
			uni.setStorageSync('isShowLoading', false);
		}
	});
}
util.getSb = () => {
	let info = getApp().globalData.sb;
	if (info) {
		return info
	} else {
		info = uni.getSystemInfoSync()
		// console.log(info)
		// let rate=uni.upx2px(750)/750,
		let rate = +(info.windowWidth / 750).toFixed(5),
			customNavh = info.statusBarHeight + 44
		getApp().globalData.sb = {
			...info,
			rate,
			customNavh,
		}
		return getApp().globalData.sb
	}
}
util.getPage = (i = 2) => {
	let pages = getCurrentPages()
	return pages[pages.length - i]
}
util.getRoute = () => {
	let pages = getCurrentPages(),
		currentPage = pages[pages.length - 1],
		url = currentPage.route || currentPage.__route__ //当前页面url
	//console.log(currentPage, currentPage.__route__, typeof currentPage)
	return url
}
util.preImg = (option) => {
	uni.previewImage({
		current: option.idx,
		urls: option.urls
	})
}
util.getSetting = (type) => {
	return new Promise((resolve, reject) => {
		uni.getSetting({
			success: (res) => {
				if (res.authSetting['scope.' + type]) {
					resolve(1);
				} else {
					resolve(2);
				}
				console.log(res.authSetting)
			}
		});
	});
}
util.setNT = (n) => {
	uni.setNavigationBarTitle({
		title: n
	})
}
util.setNB = (n = '#fff', nofc = false) => {
	uni.setNavigationBarColor({
		frontColor: n.indexOf('#fff') > -1 || nofc ? '#000000' : '#ffffff',
		backgroundColor: n,
	})
}
util.fz = (n) => {
	uni.setClipboardData({
		data: n,
		success() {
			util.message('复制成功', 1)
			console.log('success');
		}
	});
}
// 微信公众号授权
util.wxAuthorize = () => {
	let link = window.location.href;
	let params = utils.getUrlParams(link); // 地址解析

	// 已经授权登录过的就不用再授权了
	// if (store.state.token) return;

	// 如果拿到code，调用授权接口，没有拿到就跳转微信授权链接获取
	if (params.code) {
		console.log(params)
		// api.wxAuth(params.code); // 调用后台接口，授权
	} else {
		let appid = 'wx268d2c77f8c641fa';
		let uri = encodeURIComponent(link);
		let authURL =
			`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${uri}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`;
		window.location.href = authURL;
	}
}
util.mpShare = (obj) => {
	// console.log(obj,obj.p ? '/' + obj.p : '',)
	return {
		title: obj.t || '进来看看吧！',
		imageUrl: obj.i,
		// #ifndef MP-ALIPAY
		path: obj.p ? '/' + obj.p : '',
		// #endif
		// #ifdef MP-ALIPAY
		path: obj.p || '',
		// #endif
	}
}
util.sj = () => {
	let r = Math.floor(Math.random() * 2 + 0);
	return r
}

/**
 * 文件上传
 * @param {Array} filePath 上传的文件列表
 * */
util.UpLoadFile = function(filePath = []) {
	return new Promise((resove, reject) => {
		let PicList = [];
		let RunDomainName = uni.getStorageSync("account");
		// 获取url 微擎版或独立版
		let url = RunDomainName.isDev == 1 ?
			'https://' + RunDomainName.domainUrl + '/index.php/merchant/common/upload' : 'https://' +
			RunDomainName.domainUrl +
			'/index.php/merchant/common/upload';
		console.log(3)
		console.log(filePath)
		filePath.forEach(item => {
			uni.uploadFile({
				url: url,
				filePath: item,
				name: 'file',
				header: {
					'storeid': RunDomainName ? RunDomainName.storeid : "43",
					'uniacid': RunDomainName ? RunDomainName.uniacid : "43",
					'module': "yb_ps",
					'userId': RunDomainName ? RunDomainName.userId : "",
					'appType': 'apk'
				},
				success: msg => {
					if (msg.statusCode == 200) {
						PicList.push(msg.data)
					}
					if (PicList.length == filePath.length) {
						resove(PicList)
					}
				},
				fail: err => {
					console.log(err)
				}
			});
		})
	})
}

util.file_select = function(data = {}) {
	let obj = {
		count: data.count || 1,
		sourceType: data.sourceType || ["camera", "album"],
		quality: data.quality || 30
	}
	return new Promise((resove, reject) => {
		const data = uni.chooseImage({
			count: obj.count,
			sizeType: ['compressed'],
			sourceType: obj.sourceType,
			complete: async res => {
				if (res.errMsg == 'chooseImage:ok') {
					resove(await Promise.all(res.tempFiles.map(async item => {
						return await new Promise((res, rej) => {
							// #ifdef APP-PLUS
							void plus.zip.compressImage({
									src: item.path,
									overwrite: false,
									// dst: item.path + 1,
									quality: obj.quality,
								},
								msg => {
									res(msg.target)
								},
								err => {
									res(item.path)
								}
							)
							// #endif

							// #ifndef APP-PLUS
							res(item.path)
							// #endif
						})
					})))
				}
			}
		})
	})
}
export default util;
